#include "threadpool.h"


//TCP 是一个字节流协议，消息没有边界

void func_gets_filename(task_t *ptask)
{
    //客户端下载文件文件
    char *otherbuf;
    char *fileargc=strtok_r(ptask->data," ",&otherbuf);
    char filename[100]={0};
    strncpy(filename,fileargc,strlen(fileargc));
    printf("filename:%s\n",filename);
    printf("ptask->peer%d\n",ptask->peerfd);
    func_gets_file(ptask->peerfd,filename);
}

int func_gets_file(int peerfd, char *filename)
{
    //1.读取本地文件
    printf("in func_gtes_file filename:%s\n",filename);
    int fd=open(filename,O_RDWR);
    printf("fd:%d\n",fd);
    if(fd==-1)
    {
        train_t info_train;
        memset(&info_train,0,sizeof(info_train));
        info_train.length=strlen("server haven't the file，please try again");
        strcpy(info_train.buff,"server haven't the file，please try again");
        send(peerfd,&info_train,4+info_train.length,MSG_WAITALL);
        return -1;
    }
    train_t train2;
    memset(&train2,0,sizeof(train2));
    train2.length=strlen("server transfer");
    strcpy(train2.buff,"server transfer");
    send(peerfd,&train2,4+train2.length,MSG_WAITALL);
    //先发文件名
    train_t train;
    memset(&train,0,sizeof(train));
    train.length=strlen(filename);
    strcpy(train.buff,filename);
    int ret=send(peerfd,&train,4+train.length,MSG_WAITALL);

    //接收客户端的本地文件长度
    off_t localfilelen = 0;
    recv(peerfd, &localfilelen, sizeof(off_t), MSG_WAITALL);
    printf("func_gets::server recv localfilelen = %ld\n", localfilelen);
    //lseek(fd, localfilelen, SEEK_SET);//偏移文件指针
    //再发文件内容
    //3.1 获取文件长度
    struct stat st;
    fstat(fd,&st);
    printf("file length:%ld\n",st.st_size);
    send(peerfd,&st.st_size,8,MSG_WAITALL);//发送文件大小
    //进行映射mmap
    char *pbuf=(char*)mmap(NULL,st.st_size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    st.st_size -= localfilelen;
    ret=send(peerfd,pbuf + localfilelen,st.st_size,MSG_WAITALL);
    printf(">>>send ret:%d\n",ret);
    munmap(pbuf,st.st_size);
    close(fd);
    return 0;
}


